import {reqUserCode,reqUserRegisterInfo,reqUserLogin,reqUserInfo,reqLoginOut} from '../../api';
// 引入 获取本地存储 方法
import { getToken } from '../../utils/token';
const actions = {
  // 获取用户验证码
  async getUserCode({commit},phone){
    let result = await reqUserCode(phone)
    // 正常来说到这一步用户就能获取验证码自己输入了 目前是测试所以自己获取自己输入 如果发送手机上 会需要一定的短息费用
    if(result.code === 200){
      commit('GETUSERCODE',result.data)
      return "ok"
    }else{
      return Promise.reject(new Error('验证码获取失败'))
    }
  },
  // 获取用户注册时的信息
  async getUserRegisterInfo({commit},{phone,code,password}){
    let result = await reqUserRegisterInfo({phone,code,password})
    // console.log('-------------------------',result)
    if(result.code === 200){
      return 'ok'
    }else{
      return Promise.reject(new Error(`注册失败，${result.message}`))
    }
  },
  // 获取登录用户信息
  async getUserLogin({commit},{phone,password}){
    let result = await reqUserLogin({phone,password})
    if(result.code === 200){
      commit('GETUSERLOGIN',result.data)
      return 'ok'
    }else{
      return Promise.reject(new Error(`账号或密码错误`))
    }
  },
  // 获取用户 token 对应的信息
  async getUserInfo({commit}){
    let result = await reqUserInfo()
    if(result.code === 200){
      // console.log('getUserInfo',result)
      commit('GETUSERINFO',result.data)
      return 'ok'
    }else{
      return Promise.reject(new Error('token已过期,请重新登录'))
    }
  },
  // 退出登录
  async loginOut({commit}){
    let result = await reqLoginOut()
    if(result.code === 200){
      commit('LOGINOUT')
      // console.log(result)
      return 'ok'
    }else{
      Promise.reject(new Error(`退出失败了${result.message}`))
    }
  }
}
const mutations = {
  GETUSERCODE(state,code){
    state.code = code
  },
  GETUSERLOGIN(state,data){
    state.token = data.token
  },
  GETUSERINFO(state,data){
    state.userName = data
  },
  LOGINOUT(state){
    state.userName = '',
    localStorage.removeItem('TOKEN')
  }
}
const state = {
  code:'请输入手机号',
  token:getToken(),
  userName: {},
}
const getters = {}

export default {
  namespaced:true,
  actions,
  mutations,
  state,
  getters
}